package com.jy.api.dao;

import com.jy.api.domain.Coupon;
import com.jy.api.domain.CouponStatus;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigInteger;
import java.util.Date;
import java.util.List;

/**
 * Created by lihu on 2017/11/17.
 */
public interface CouponDao extends CrudRepository<Coupon, String> {

    /**
     * 获取店铺优惠卷信息
     *
     * @param storeId
     * @param enabled
     * @return
     */
    Page<Coupon> findListByStoreIdAndEnabledAndEndTimeAfter(String storeId, boolean enabled, Date time, Pageable pageable);


    List<Coupon> findListByStoreIdAndEnabled(String storeId,boolean enabled);


    /**
     * 获取店铺优惠卷信息
     *
     * @param storeId
     * @param enabled
     * @return
     */
    Page<Coupon> findListByStoreIdAndEnabledAndStartTimeLessThanEqualAndEndTimeGreaterThan(String storeId, boolean enabled,Date startDate,Date date, Pageable pageable);


    List<Coupon> findListByIdIn(List<String> ids);


    List<Coupon> findByStoreIdAndStatusIn(String storeId, List<CouponStatus> statuses);

    Page<Coupon> findByStoreIdAndStatusIn(String storeId, List<CouponStatus> statuses,Pageable pageable);

    Page<Coupon> findByStoreIdAndStatus(String storeId, CouponStatus statuses,Pageable pageable);


    List<Coupon> findByStatus(CouponStatus statuses);

    List<Coupon> findByStatusIn(List<CouponStatus> statuses);
    /**
     * 获取店铺所有优惠卷种类信息
     *
     * @param storeId
     * @return
     */
    List<Coupon> findListByStoreIdOrderByEnabledDesc(String storeId);

    @Query(value = "SELECT c.`title` ,ci.`begin_time` , ci.`end_time` FROM `coupon_instance` ci LEFT JOIN `coupon` c on ci.`coupon_id`= c.`id` WHERE ci. `store_id` =? AND  ci.`stauts`= 'NORMAL' AND ci.`owner_id`=? AND c.`enabled`= 1 AND c.`end_time` >=? ORDER BY ci.`end_time`  DESC ", nativeQuery = true)
    List<Object[]> findByStoreId(String storeId,String memberId,Date date);



    @Query(value = "SELECT COUNT(ci.`id`)  FROM `coupon_instance` ci LEFT JOIN `coupon` c on ci.`coupon_id`= c.`id` WHERE ci. `store_id`= ? AND ci.`stauts`= 'VERIFIED'  AND ci.`owner_id`= ? ", nativeQuery = true)
    BigInteger findUseCoupon(String storeId, String memberId);


    @Modifying
    @Transactional
    @Query(value = "UPDATE `coupon` set `stauts` ='EXPIRED' WHERE `owner_id`=?  AND `store_id` =?   AND `end_time` <=? AND `stauts` ='NORMAL' " ,nativeQuery = true)
    void updateCouponStatus(String storeId);
}
